//package com.magenta.maxoptra.geocoding.geobase;
//
//import com.magenta.maxoptra.gis.utils.LineUnits;
//import com.magenta.maxoptra.commons.utils.DateTimeHelper;
//import com.magenta.maxoptra.commons.utils.SimpleProfiler;
//import com.magenta.maxoptra.gis.commons.StringUtils;
//import com.magenta.maxoptra.commons.utils.UnitsConverter;
//import com.magenta.maxoptra.dto.GeoLocationRecord;
//import com.magenta.maxoptra.geocoding.geobase.webservice.*;
//import com.magenta.maxoptra.gis.*;
//import com.magenta.maxoptra.gis.GeoException;
//import com.magenta.maxoptra.gis.GeoProviderSettings;
//import com.magenta.maxoptra.gis.GeoRoute;
//import com.magenta.maxoptra.gis.GeographicCoordinates;
//import com.magenta.maxoptra.gis.GeoAddress;
//import org.apache.commons.httpclient.URIException;
//import org.apache.commons.lang.BooleanUtils;
//import org.apache.http.HttpResponse;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.util.EntityUtils;
//
//import javax.xml.namespace.QName;
//import java.io.IOException;
//import java.net.URL;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Properties;
//
//import static com.magenta.maxoptra.gis.GisParameter.server_ip;
//import static com.magenta.maxoptra.gis.GisParameter.use_shortest_route;
//
///**
// * @author Zaur Muhametgaleev
// * @version 9/21/11 5:41 PM
// * @see "jira task MRS-4025: Интеграция с GeoBase"
// * @since Maxoptra 3 (GT)
// */
//@Deprecated
//public class OldGeoProviderGeoBaseImpl extends AbstractProviderGeoBase implements IGeocoding, IGeoRouting, IReverseGeocoding {
//
//
//
//    private GeoBaseWsSoap geoBaseWsSoap;
//
//    protected static final String START_TAG = "points_cache:{";
//    protected static final String END_TAG = ",error:null,id:2}";
//    protected static final String POINTS_CACHE = "points_cache";
//
//    public List<GeoAddress> findAddressByKeyword(GeoProviderSettings settings, String keyword, int i) throws GeoException {
//
//        SimpleProfiler profiler = new SimpleProfiler(isLoggingAllowed(), "FIND_ADDRESS_BY_KEYWORD");
//
//        List<GeoAddress> result = new ArrayList<GeoAddress>();
//
//        GeoBaseWsSoap port = getPort();
//        SimpleProfiler profilerQuery = new SimpleProfiler(isLoggingAllowed(), "GEOBASE_QUERY");
//        Country country = getCountry(settings);
//        ArrayOfSurrogateGeocodeAddress geoBaseAddresses = port.forwardGeocodeNatural(null, keyword, country);
//        profilerQuery.logDuration();
//
//        SimpleProfiler profilerResult = new SimpleProfiler(isLoggingAllowed(), "GEOBASE_PARSE_RESULT");
//        if (geoBaseAddresses != null) {
//            List<SurrogateGeocodeAddress> surrogateGeocodeAddress = geoBaseAddresses.getSurrogateGeocodeAddress();
//            if (surrogateGeocodeAddress != null && !surrogateGeocodeAddress.isEmpty()) {
//                SurrogateGeocodeAddress geoBaseAddress = surrogateGeocodeAddress.get(0);
//                GeoAddress resultAddress = createGeoBaseAddress(geoBaseAddress);
//                result.add(resultAddress);
//            }
//        }
//        profilerResult.logDuration();
//
//        profiler.logDuration();
//
//        return result;
//    }
//
//    public GeoAddress findBestAddressByKeyword(GeoProviderSettings settings, String keyword) throws GeoException {
//        SimpleProfiler profiler = new SimpleProfiler(isLoggingAllowed(), "FIND_BEST_ADDRESS_BY_KEYWORD");
//
//        GeoBaseWsSoap port = getPort();
//
//        SimpleProfiler profilerQuery = new SimpleProfiler(isLoggingAllowed(), "GEOBASE_QUERY");
//        ArrayOfSurrogateGeocodeAddress geoBaseAddresses = port.forwardGeocodeNatural(null, keyword, getCountry(settings));
//        profilerQuery.logDuration();
//
//        SimpleProfiler profilerResult = new SimpleProfiler(isLoggingAllowed(), "GEOBASE_PARSE_RESULT");
//        GeoAddress address = null;
//        if (geoBaseAddresses != null) {
//            List<SurrogateGeocodeAddress> surrogateGeocodeAddress = geoBaseAddresses.getSurrogateGeocodeAddress();
//            if (surrogateGeocodeAddress != null && !surrogateGeocodeAddress.isEmpty()) {
//                SurrogateGeocodeAddress geoBaseAddress = surrogateGeocodeAddress.get(0);
//                address = createGeoBaseAddress(geoBaseAddress);
//            }
//        }
//        profilerResult.logDuration();
//
//        profiler.logDuration();
//
//        return address;
//    }
//
//    @Override
//    public List<GeoAddress> doForwardGeocoding(GeoProviderSettings settings, GeoAddress address, int resultAddressLimit) throws GeoException {
//        SimpleProfiler profiler = new SimpleProfiler(isLoggingAllowed(), "DO_FORWARD_GEOCODING");
//
//        if (address == null) {
//            throw new IllegalArgumentException("Address is not specified");
//        }
//
//
//        GeoBaseWsSoap port = getPort();
//
//        Country country = getCountry(settings);
//
//        // do Forward geocoding
//        SimpleProfiler profilerQuery = new SimpleProfiler(isLoggingAllowed(), "GEOBASE_QUERY");
//        ArrayOfSurrogateGeocodeAddress gbAddresses = port.forwardGeocode("",
//                address.getHouse(),
//                address.getStreet(),
//                address.getCity(),
//                address.getState(),
//                address.getZip(),
//                country);
//        profilerQuery.logDuration();
//
//        SimpleProfiler profilerResult = new SimpleProfiler(isLoggingAllowed(), "GEOBASE_PARSE_RESULT");
//        List<GeoAddress> results = new ArrayList<GeoAddress>();
//        if (gbAddresses != null) {
//            for (SurrogateGeocodeAddress gbAddress : gbAddresses.getSurrogateGeocodeAddress()) {
//                GeoAddress result = new GeoAddress();
//                result.setCity(gbAddress.getCity());
//                result.setZip(gbAddress.getPostalCode());
//                result.setCountry(gbAddress.getStreet());
//                result.setLatitude(gbAddress.getLatitude());
//                result.setLongitude(gbAddress.getLongitude());
////                result.setInfo(gbAddress.getLine1());
//
//                results.add(result);
//            }
//        }
//
//        profilerResult.logDuration();
//
//        profiler.logDuration();
//
//        return results;
//    }
//
//
//    @Override
//    public synchronized GeoRoute getRoute(GeographicCoordinates from, GeographicCoordinates to) throws GeoException {
//        SimpleProfiler profiler = new SimpleProfiler(isLoggingAllowed(), "GET_ROUTE");
//
//        GeoBaseWsSoap port = getPort();
//
//        WsLatLon gbFrom = new WsLatLon();
//        double fLat = from.getLatitude();
//        double fLon = from.getLongitude();
//        gbFrom.setLat(fLat);
//        gbFrom.setLon(fLon);
//
//        WsLatLon gbTo = new WsLatLon();
//        double tLat = to.getLatitude();
//        double tLon = to.getLongitude();
//        gbTo.setLat(tLat);
//        gbTo.setLon(tLon);
//
//        SimpleProfiler profilerQueryDistance = new SimpleProfiler(isLoggingAllowed(), "GEOBASE_QUERY_DISTANCE_AND_DURATION");
//        RouteInfo routeInfo = port.routeDistanceAndDurationByCoordinates(gbFrom, gbTo, getRouteSettings());
//        double distance = routeInfo.getDistance();
//        double duration = UnitsConverter.convert(LineUnits.MILE, LineUnits.KILOMETRE, routeInfo.getDuration());
//        profilerQueryDistance.logDuration();
//
//        duration *= DateTimeHelper.MSECS_IN_MINUTE;
//        long lngDuration = new Double(duration).longValue();
//
//
//        if (isLoggingAllowed()) {
//            logger.info("Route information: from[%s, %s], to[%s, %s], distance=%s, duration=%s",
//                    fLat, fLon, tLat, tLon, distance, duration);
//        }
//        GeoRoute geoRoute = new GeoRoute(distance, lngDuration, from, to);
//
//        profiler.logDuration();
//
//        return geoRoute;
//    }
//
//    @Override
//    public synchronized List<GeoLocationRecord> getRoutePoints(GeoProviderSettings settings,
//                                                               GeographicCoordinates from,
//                                                               GeographicCoordinates to) throws GeoException {
//        SimpleProfiler profiler = new SimpleProfiler(isLoggingAllowed(), "GET_ROUTE_POINTS");
//
//        List<GeoLocationRecord> result = new ArrayList<GeoLocationRecord>();
//
//        String ip = settings.getGisParams().get(server_ip.withProvider(getProviderName()));
//        if (StringUtils.isEmpty(ip)) {
//            logger.error("GeoBase IP is not presented");
//            return result;
//        }
//
//        Properties props = client.getProperties();
//        String useShortestRouteStr = props.getProperty(use_shortest_route.withProvider(getProviderName()));
//        boolean useShortestRoute = BooleanUtils.toBoolean(useShortestRouteStr);
//
//        String requestResult = doRequest(from, to, ip, useShortestRoute);
//        if (StringUtils.isEmpty(requestResult)) {
//            return result;
//        }
//
//        extractRoutePoints(result, requestResult);
//
//        logger.info("Get route points. Points count: " + result.size());
//
//        profiler.logDuration();
//
//        return result;
//    }
//
//    public synchronized List<GeoLocationRecord> getRoutePoints(GeoProviderSettings settings, List<GeographicCoordinates> coordinates) throws GeoException {
//        throw new UnsupportedOperationException("getRoutePoints by list of coordinates is not supported for GeoBase");
//    }
//
//    protected void extractRoutePoints(List<GeoLocationRecord> result, String requestResult) {
//        SimpleProfiler profiler = new SimpleProfiler(isLoggingAllowed(), "EXTRACT_ROUTE_POINTS");
//
//        String points = requestResult.replaceFirst(".*points_cache:\\{.*,_values:(_\\[[1-9]{1,3}\\]=)?\"([^\"]*)\".*", "$2");
//        if (StringUtils.isNotEmpty(points)) {
//            String[] splittedPointsString = points.trim().split(";");
//            for (String point : splittedPointsString) {
//                if (StringUtils.isNotEmpty(point)) {
//                    String[] pointDetails = point.trim().split(",");
//                    if (pointDetails.length == 2
//                            && StringUtils.isNotEmpty(pointDetails[0])
//                            && StringUtils.isNotEmpty(pointDetails[1])) {
//                        Double latitude = Double.parseDouble(pointDetails[0]);
//                        Double longitude = Double.parseDouble(pointDetails[1]);
//                        result.add(new GeoLocationRecord(longitude, latitude));
//                    }
//                }
//            }
//        }
//
//        profiler.logDuration();
//    }
//
//    private String doRequest(GeographicCoordinates from, GeographicCoordinates to, String ip, boolean useShortestRoute) {
//        SimpleProfiler profiler = new SimpleProfiler(isLoggingAllowed(), "DO_REQUEST");
//
//        String routingStrategy = useShortestRoute ? "Shortest" : "Fastest";
//
//        String request = "http://" + ip + "/GeoStream/route.ashx?p={id:2,method:\"GetDirectionsStateless\"," +
//                "requestUncompressedJson:null,params:[{Start:null,End:null,Strategy:{ExtraProcessingRatio:30," +
//                "AllowUTurns:true,_class:[\"Telogis.GeoBase.Routing.RoutingStrategy" + routingStrategy +
//                "\",_[8]=\"geobase.net\"],RoadCrossingBehavior:\"Allowed\",UseTollRoads:true},Stops:[{Location:{" +
//                "Lat:" + from.getLatitude() + ",Lon:" + from.getLongitude() +
//                ",_class:_[13]=[\"Telogis.GeoBase.LatLon\",{_ref:8}]}," +
//                "_class:_[15]=[\"Telogis.GeoBase.RouteStop\",{_ref:8}]},{" +
//                "Location:{Lat:" + to.getLatitude() + ",Lon:" + to.getLongitude() + ",_class:{_ref:13}}," +
//                "_class:{_ref:15}}],TrafficSource:null,_class:[\"Telogis.GeoBase.Routing.Route\",{_ref:8}]}]," +
//                "_class:[\"Telogis.GeoBase.GeoStream.JSONRequest\",{_ref:8}]," +
//                "clientVersion:\"3.7.0.0\"}";
//
//        if (isLoggingAllowed()) {
//            logger.info(request);
//        }
//
//        String requestResult = null;
//        try {
//            String encodedUrl = org.apache.commons.httpclient.util.URIUtil.encodeQuery(request);
//            HttpGet get = new HttpGet(encodedUrl);
//            HttpResponse response = client.execute(get);
//            requestResult = EntityUtils.toString(response.getEntity());
//        } catch (URIException e) {
//            logger.error(e.getMessage());
//        } catch (IOException e) {
//            logger.error(e.getMessage());
//        }
//
//        profiler.logDuration();
//
//        return requestResult;
//    }
//
//    private GeoBaseWsSoap getPort() {
//        SimpleProfiler profiler = new SimpleProfiler(isLoggingAllowed(), "GET_PORT");
//
//        if (geoBaseWsSoap == null) {
//            QName qname = new QName("http://www.telogis.com/geobase/", "GeoBaseWs");
//            URL wsdlLocation = getURL();
//            try {
//                if (proxy != null) {
//                    wsdlLocation.openConnection(proxy);
//                } else {
//                    wsdlLocation.openConnection();
//                }
//            } catch (IOException e) {
//                logger.error(e);
//            }
//            GeoBaseWs webService = new GeoBaseWs(wsdlLocation, qname);
//            geoBaseWsSoap = webService.getGeoBaseWsSoap12();
//        }
//
//        profiler.logDuration();
//        return geoBaseWsSoap;
//    }
//
//    @Override
//    public String getProviderName() {
//        return "geobase-old";
//    }
//
//
//    @Override
//    public synchronized GeoAddress doReverseGeocoding(GeographicCoordinates geoCoordinates) throws GeoException {
//        SimpleProfiler profiler = new SimpleProfiler(isLoggingAllowed(), "DO_REVERSE_GEOCODING");
//
//        GeoAddress result = null;
//
//        GeoBaseWsSoap port = getPort();
//
//        ArrayOfWsLatLon points = new ArrayOfWsLatLon();
//        List<WsLatLon> wsLatLon = points.getWsLatLon();
//        WsLatLon location = new WsLatLon();
//        location.setLat(geoCoordinates.getLatitude());
//        location.setLon(geoCoordinates.getLongitude());
//        wsLatLon.add(location);
//
//        SimpleProfiler profilerQuery = new SimpleProfiler(isLoggingAllowed(), "GEOBASE_QUERY");
//        ArrayOfAddressWithStreetLink addressWithStreetLink = port.reverseGeocodeFull(null, points);
//        profilerQuery.logDuration();
//
//        SimpleProfiler profilerResult = new SimpleProfiler(isLoggingAllowed(), "GEOBASE_QUERY_RESULT");
//        if (addressWithStreetLink != null &&
//                addressWithStreetLink.getAddressWithStreetLink() != null &&
//                addressWithStreetLink.getAddressWithStreetLink().size() > 0) {
//            AddressWithStreetLink link = addressWithStreetLink.getAddressWithStreetLink().get(0);
//            if (link.getAddress() != null) {
//                result = buildGeoAddress(link, geoCoordinates);
//            }
//
//        }
//
//        profilerResult.logDuration();
//
//        profiler.logDuration();
//
//        return result;
//    }
//
//    @Override
//    public List<GeoAddress> doReverseGeocodeFull(List<GeographicCoordinates> geoCoordinates) throws GeoException {
//        SimpleProfiler profiler = new SimpleProfiler(isLoggingAllowed(), "DO_REVERSE_GEOCODING");
//
//        List<GeoAddress> addresses = new ArrayList<GeoAddress>();
//
//        GeoBaseWsSoap port = getPort();
//
//        ArrayOfWsLatLon points = new ArrayOfWsLatLon();
//        List<WsLatLon> wsLatLon = points.getWsLatLon();
//        for (GeographicCoordinates coordinates : geoCoordinates) {
//            WsLatLon location = new WsLatLon();
//            location.setLat(coordinates.getLatitude());
//            location.setLon(coordinates.getLongitude());
//            wsLatLon.add(location);
//        }
//
//        SimpleProfiler profilerQuery = new SimpleProfiler(isLoggingAllowed(), "GEOBASE_QUERY");
//        List<AddressWithStreetLink> addressWithStreetLinks = port.reverseGeocodeFull(null, points).getAddressWithStreetLink();
//        profilerQuery.logDuration();
//
//        SimpleProfiler profilerResult = new SimpleProfiler(isLoggingAllowed(), "GEOBASE_QUERY_RESULT");
//
//        for (AddressWithStreetLink addressLink : addressWithStreetLinks) {
//            if (addressLink.getAddress() != null) {
//                addresses.add(buildGeoAddress(addressLink, null));
//            }
//        }
//        profilerResult.logDuration();
//
//        profiler.logDuration();
//
//        return addresses;
//    }
//
//    @Override
//    public GeoRoute getRoute(List<GeographicCoordinates> coordinates) throws GeoException {
//        throw new UnsupportedOperationException("getRoute by list of coordinates is not supported for general GeoBaseProvider");
//    }
//
//    @Override
//    public List<GeoRoute> getRoute(GeographicCoordinates from, List<? extends GeographicCoordinates> to, int timeout) throws GeoException {
//        throw new UnsupportedOperationException("getRoute from coordinate to list of coordinates is not supported for OldGeoProviderGeoBase");
//    }
//
//}
